<template>
  <div class="container">
    <div class="chart-title">{{title}}</div>
    <div :id="props.id" class="echarts-block"></div>
  </div>
</template>

<script setup lang="ts" name="GaugeCom">
import { onMounted, ref, computed, watch, onBeforeUnmount } from 'vue'
import * as Echarts from 'echarts'

const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  type: {
    type: Number,
    default: 0
  },
  sum: {
    type: Number,
    default: 0
  },
  options: {
    type: Object,
    default: () => {}
  }
})

const title = computed(() => {
  let str = ''
  switch (props.type) {
    case 1: 
      str = 'CPU占用'
      break
    case 2: 
      str = '内存占用'
      break
    case 3: 
      str = '储存空间'
      break
  }
  return str
})
let gc: echarts.ECharts
const chartOptions = <any>{
  series: [
    {
      type: 'gauge',
      radius: '80%',
      progress: {
        show: true,
        width: 10,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: '#26cfd7'
            }, {
              offset: 1, color: '#13e2aa'
            }],
            global: false
          }
        }
      },
      axisLine: {
        lineStyle: {
          width: 10
        }
      },
      axisTick: {
        show: false
      },
      splitLine: {
        show: false
      },
      axisLabel: {
        show: false
      },
      anchor: {
        show: true,
        showAbove: false,
        size: 14,
        itemStyle: {
          borderWidth: 8,
          borderColor: '#68f8e5',
          color: '#02a7f0',
          shadowColor: '#02a7f0',
          shadowBlur: 2
        }
      },
      pointer: {
        length: '100%',
        width: 1,
        itemStyle: {
          color: '#02a7f0'
        }
      },
      detail: {
        valueAnimation: true,
        fontSize: 16,
        offsetCenter: [0, '110%'],
        color: '#09BB07',
        formatter: (value: any) => `${value}%`
      },
      data: [
        {
          value: props.sum
        }
      ]
    }
  ]
}

watch(() => props.options, (newVal) => {

}, {
  deep: true
})

onMounted(() => {
  initCharts()
  window.addEventListener('resize', resizeCharts, false)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts, false)
})

// 初始化图表
const initCharts = () => {
  let gaugeCharts = document.getElementById(props.id) as HTMLElement
  gc = Echarts.init(gaugeCharts)
  gc.setOption(chartOptions)
}

// 调整charts窗口
const resizeCharts = () => {
  gc.resize()
}
</script>

<style lang="stylus">
.container
  .chart-title
    font-size 16px
  .echarts-block
    width 100%
    height 100px
</style>
